package com.rxyb.security.handler;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.rxyb.security.db.dao.SysMenuResouceMapper;
import com.rxyb.security.db.dao.SysRoleMenuMapper;
import com.rxyb.security.db.po.SysMenuResouce;
import com.rxyb.security.db.po.SysRoleMenu;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;

/**
 * @author YJH
 * @version 1.0
 * @description
 * @date 2020/7/7 17:36
 */
@Slf4j
@Component
public class UrlRolesFilterHandler implements FilterInvocationSecurityMetadataSource {

    @Autowired
    private SysMenuResouceMapper sysMenuResouceMapper;

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {

        log.info("动态获取url:" + ((FilterInvocation) object).getRequestUrl());

        List<SysMenuResouce> sysMenuResouces = sysMenuResouceMapper.selectList(new QueryWrapper<SysMenuResouce>().lambda().eq(SysMenuResouce::getMenuUrl, ((FilterInvocation) object).getRequestUrl()));
        String[] names = new String[sysMenuResouces.size()];
        if (!sysMenuResouces.isEmpty()) {
            for (int i = 0; i < sysMenuResouces.size(); i++) {
                names[i] = sysMenuResouces.get(i).getMenuName();
            }
        }
        return SecurityConfig.createList(names);
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return FilterInvocation.class.isAssignableFrom(clazz) ;
    }
}
